package com.huidian.gitbatchprocessing.ui.service;

import org.reflections.Reflections;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * 分支操作工厂
 *
 * @author zxb
 * @date 20201/6/18
 */
public class BranchOperateFactory {

    /**
     * 存储分支操作对应的实现类
     */
    private static final Map<Byte, AbstractBranchOperate> BRANCH_OPT_MAP;

    static {
        Map<Byte, AbstractBranchOperate> map = new LinkedHashMap<>();
        // 获取分支操作接口的所有实现类
        Reflections reflections = new Reflections("com.huidian.gitbatchprocessing");
        Set<Class<? extends AbstractBranchOperate>> subTypesOf = reflections.getSubTypesOf(AbstractBranchOperate.class);
        for (Class<? extends AbstractBranchOperate> clazz : subTypesOf) {
            try {
                AbstractBranchOperate branchOperate = clazz.getDeclaredConstructor().newInstance();
                map.put(branchOperate.getKey(), branchOperate);
            } catch (Exception e) {
                // pass
            }
        }
        BRANCH_OPT_MAP = map;
    }

    public static AbstractBranchOperate getInstance(Byte optKey) {
        return Optional.ofNullable(BRANCH_OPT_MAP.get(optKey)).orElseThrow(() -> new IllegalArgumentException("操作不存在"));
    }
}